//
//  HomeController.swift
//  chaorenWeibo
//
//  Created by tanchao on 15/7/28.
//  Copyright © 2015年 chaoren. All rights reserved.
//

import UIKit
class HomeController: BaseTableViewController {
    /// 微博数据
    var statuses : [Status]?{
        didSet{
            tableView.reloadData()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        if !UserAccount.didLogon{
            visitorView?.setupVisitorViewInfo(true, imageName: "visitordiscover_feed_image_smallicon", message: "关注一些人，回这里看看有什么惊喜")
            return
        }
        preparetabelView()
        loadStutas()
    }
    private var pullupRefreshFlag = false
    private var tipShowing = false
    //MARK:- 加载数据
    func loadStutas(){
        refreshControl?.beginRefreshing()
        if tipShowing{
            refreshControl?.endRefreshing()
            print("正在刷新，请等待")
            return
        }
        var since_id = statuses?.first?.id ?? 0
        // 判断是否是上拉刷新
        var max_id = 0
        if pullupRefreshFlag {
            since_id = 0
            max_id = statuses?.last?.id ?? 0
        }
        tipShowing = since_id > 0
        Status.loadStatus(since_id, max_id: max_id) { (dataList, error) -> () in
            // 关闭刷新控件，结束刷新动画
            self.refreshControl?.endRefreshing()
            if error != nil {
                print(error)
                return
            }
            let count = dataList?.count ?? 0
//            print("刷新到 \(count) 条数据")
            // 只有下拉刷新才需要提示
            if since_id > 0 {
                self.showPulldownTip(count)
            }
            
            // 如果没有数据，直接返回
            if count == 0 {
                self.pullupRefreshFlag = false
                return
            }
            
            if since_id > 0 {       // 做下拉刷新，应该将结果集合放在之前数组的前面
                self.statuses = dataList! + self.statuses!
            } else if max_id > 0 {  // 做上拉刷新，应该讲结果集合放在数组的后面
                self.statuses! += dataList!
                
                // 复位上拉刷新标记，保证下一次仍然能够上拉
                self.pullupRefreshFlag = false
            } else {
                self.statuses = dataList
            }

        }
        
    }
    /// 刷新微博提示动画
    private func showPulldownTip(count:Int){
        tipLabel.text = (count == 0) ? "暂时没有新的微博":"更新了\(count)条微博"
//        print(tipLabel.text)
        let rect = tipLabel.frame
//         print("开始时间 \(NSDate())")
        UIView.animateWithDuration(2.0, animations: { () -> Void in
            UIView.setAnimationRepeatAutoreverses(true)
            self.tipLabel.frame = CGRectOffset(rect, 0, 3 * rect.height)
            }) { (_) -> Void in
                self.tipLabel.frame = rect
                self.tipShowing = false
//                 print("结束时间 \(NSDate())")
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    private func preparetabelView() {
        
        tableView.registerClass(ForWordStatusCell.self, forCellReuseIdentifier: StatusCellIdentifier.ForwardCell.rawValue)
        tableView.registerClass(NormolStatusCell.self, forCellReuseIdentifier: StatusCellIdentifier.NormalCell.rawValue)
        tableView.estimatedRowHeight = 200
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        refreshControl = WeiboRefreshControl()
        refreshControl?.addTarget(self, action: "loadStutas", forControlEvents: UIControlEvents.ValueChanged)

    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status =  statuses![indexPath.row]
        // 要求必须注册原型cell, storyboard，register Class
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellID(status), forIndexPath: indexPath) as! StatusCell
        if indexPath.row == statuses!.count - 1{
            pullupRefreshFlag = true
            loadStutas()
        }
        cell.status = status
        
        return cell
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statuses![indexPath.row]
        if let h = status.rowHeight{
            return h
        }
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellID(status)) as!StatusCell
        status.rowHeight = cell.rowHeight(status)
        return status.rowHeight!
    }

    lazy private  var tipLabel: UILabel = {
        let h:CGFloat = 44
        let object = UILabel(frame: CGRectMake(0, -2 * h, UIScreen.mainScreen().bounds.width,h))
        object.backgroundColor = UIColor.orangeColor()
        object.textColor = UIColor.whiteColor()
        object.textAlignment = NSTextAlignment.Center
        self.navigationController?.navigationBar.insertSubview(object, atIndex: 0)
        return object
        }()
}
